package com.icexxx.litchi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.client.RestTemplate;

@Configuration
@ConditionalOnClass({ ResourceLoaderAware.class, RestTemplate.class, TomcatWebServer.class })
@AutoConfigureAfter(TomcatWebServer.class)
public class LitchiAutoConfiguration implements ResourceLoaderAware {
    @Autowired(required = false)
    private Environment environment;
    @Autowired(required = false)
    private ServerProperties serverProperties;

    private Litchi litchi;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        if (litchi == null) {
            litchi = Litchi.create(environment, serverProperties);
        }
        litchi.shutdownPort();
    }
}
